package com.xiaoma.future;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;

public class CompletableFutureDemo {

    public static void main(String[] args) throws ExecutionException, InterruptedException {
        SimpleDateFormat dateFormat=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        //回调获取completableFuture 结果，不阻塞主线程
        System.out.println("completableFuture start at "+ dateFormat.format(new Date()));
        CompletableFuture<String> complete = CompletableFuture.supplyAsync(() -> {
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            return "completablefuture finish";

        }).whenComplete((r, t) -> {

            System.out.println("complete start at "+ dateFormat.format(new Date()));
            try {
                Thread.sleep(2000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("complete:"+ r + " at " + dateFormat.format(new Date()));
        });

        System.out.println("获取结果："+complete.get()+dateFormat.format(new Date()));

    }


}
